<template>
  <canvas ref="babylonCanvas" style="width: 100vw; height: 100vh"></canvas>
</template>

<script setup>
import { onMounted, onUnmounted, ref } from "vue";
import {
  Engine,
  Scene,
  ArcRotateCamera,
  Vector3,
  HemisphericLight,
  AssetsManager,
  SceneLoader,
} from "@babylonjs/core";

const babylonCanvas = ref(null);
let engine, scene;

onMounted(() => {
  engine = new Engine(babylonCanvas.value, true);
  scene = buildScene();
  engine.runRenderLoop(() => scene.render());
  window.addEventListener("resize", resize);
});

onUnmounted(() => {
  engine.dispose();
  window.removeEventListener("resize", resize);
});

function resize() {
  engine.resize();
}

function buildScene() {
  const scene = new Scene(engine);
  const camera = new ArcRotateCamera(
    "Camera",
    Math.PI / 2,
    Math.PI / 4,
    4,
    Vector3.Zero(),
    scene
  );
  camera.attachControl(babylonCanvas.value, true);
  const light = new HemisphericLight("light", new Vector3(0, 1, 0), scene);

  const assetsManager = new AssetsManager(scene);
  const fbxTask = assetsManager.addMeshTask(
    "fbxTask",
    null,
    "/models/fbx/fountain/Fountain.fbx",
    null,
    null
  );
  fbxTask.onSuccess = (task) => {
    const meshes = task.loadedMeshes;
    meshes.forEach((mesh) => {
      mesh.isPickable = true;
    });
  };

  assetsManager.load();

  scene.onPointerObservable.add((pointerInfo) => {
    if (pointerInfo.type === 1) {
      // PointerEventTypes.POINTERDOWN
      const pickedMesh = scene.pick(pointerInfo.x, pointerInfo.y);
      if (pickedMesh && pickedMesh.pickedMesh) {
        console.log("Picked mesh:", pickedMesh.pickedMesh.name);
        // 这里可以获取到模型的属性
      }
    }
  });

  return scene;
}
</script>

<style>
.babylon-canvas {
  width: 100%;
  height: 100%;
}
</style>
